//
//  JYHomeController.m
//  JYShop
//
//  Created by 花花 on 2017/9/28.
//  Copyright © 2017年 花花. All rights reserved.
//

#import "JYHomeController.h"
#import "JYSearchBar.h"
#import "JYSearchViewController.h"
#import "JYHeaderView.h"
#import "JYFunView.h"
#import "JYFunModel.h"
#import "CategoryModel.h"
#import <MJRefresh/MJRefresh.h>
#import "JYPublicCell.h"
#import "JYHomeLeftCell.h"
#import "JYHomeViewModel.h"
#import "JYHomeBannerModel.h"
#import "BaseWebViewController.h"
#import "JYCategorysModel.h"
#import "BaseModel.h"
#import "JYHomeTableViewProxy.h"
@interface JYHomeController ()<UITableViewDataSource,UITableViewDelegate,SDCycleScrollViewDelegate,JYHomeViewModelDelegate>


@property(nonatomic) JYSearchBar *searchBar; //搜索

@property(nonatomic) JYHomeViewModel *viewModel;


@property (nonatomic, strong)JYHeaderView *header; //banner

@property (nonatomic, strong) JYFunView *funView; //功能funView 10个

@property (nonatomic) UITableView *leftTableView; //左边tableView

@property (nonatomic) UITableView *rightTableView; ////右边tableView

@property (nonatomic, strong) UITableView *scrollView;

@property(nonatomic,strong)NSMutableArray *leftArr; //tableView左边数据

@property(nonatomic,strong)NSMutableArray *rightArr; //tableView右边数据
@property(nonatomic,strong)UILabel *nameLabel;

@property(nonatomic,strong)NSMutableArray  *bannerArr; //轮播图数据

@property(nonatomic,strong)NSMutableArray  *categorysArr; //fun数据 即collectionView数据

@property(nonatomic,strong)JYHomeTableViewProxy *homeRightTableViewProxy;


@end

@implementation JYHomeController

#pragma mark - Life Cycle
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    NSLog(@"_______________离开_______________");
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
      NSLog(@"model ===%@  %@",LH.userInfor.userid,LH.userInfor.id);
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self setupSubView];
   [self loadDataFromNetwork];
  
}

- (void)loadDataFromNetwork{

    //轮播图
    [self.viewModel handlerBannerDataWithAreaId:@"d9a89941231d49b790bc2de8eb02e20f" Success:^(NSArray *lbtArr) {
       
        [self.bannerArr removeAllObjects];
        
        for (int i = 0; i<lbtArr.count; i++){
            
            JYHomeBannerModel *model = lbtArr[i];
            
            [self.bannerArr addObject:model.image];
        }
       
        self.header.imageURLStringsGroup = self.bannerArr;
        self.header.placeholderImage = [UIImage imageNamed:@"home_banner"];
        
        [self.scrollView reloadData];
        
    }];
    
    _categorysArr = [NSMutableArray array];
    
    //
    [self.viewModel  handlerCategoryDataWithSuccess:^(NSArray *categorysArr) {
       
        for (NSDictionary *dic in categorysArr) {
       
            JYCategorysModel *model = [JYCategorysModel mj_objectWithKeyValues:dic];
            
            [self.categorysArr addObject:model];
//            
            for (NSDictionary *dicChildrenList in dic[@"childrenList"]) {
                
                
                JYChildrenListMoel *model = [JYChildrenListMoel mj_objectWithKeyValues:dicChildrenList];
            
            

                [self.leftArr addObject:model];
        
                NSLog(@"%zd ----model %@",self.leftArr.count,model.name);
            }
         
            [self.leftTableView reloadData];
        }
        
        self.funView.dataArr = self.categorysArr;
        
    }];

         //右边数据
        [self.viewModel requsetHomeRithtTableList];

}

#pragma mark - setupSubView
- (void)setupSubView{
    
    [self.view addSubview:self.scrollView ];
    [self.scrollView addSubview:self.funView];
    [self.scrollView addSubview:self.leftTableView];
    [self.scrollView addSubview:self.rightTableView];
    
    JYWeakSelf;
    
    _searchBar = [[JYSearchBar alloc]initWithOffSet:125 ];
    _searchBar.searchBarClickCallBack = ^{
        JYSearchViewController *searchVc = [JYSearchViewController new];

        [weakSelf.navigationController pushViewController:searchVc animated:YES];
    };
    [self.view addSubview:_searchBar];
    
    [_searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.view.mas_left);
        make.right.equalTo(weakSelf.view.mas_right);
        make.top.equalTo(weakSelf.view.mas_top);
        make.height.equalTo(@64);
    }];
    
    [self.searchBar addSubview:self.nameLabel];
    
}

#pragma mark - <JYHomeViewModelDelegate>
- (void)homeRightTableRequestDataSuccessWithArray:(NSMutableArray *)dataArray{
    
    self.homeRightTableViewProxy.dataArray = dataArray;
    
    [self.rightTableView reloadData];
    
}

- (void)shopcartAccountFortotalCount:(double)totalCount{
    
    [self.rightTableView reloadData];
}
#pragma mark - <UITableViewDelegate && UITableViewDataSource>
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.leftArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    JYHomeLeftCell *cell = [tableView dequeueReusableCellWithIdentifier:@"leftCellID"];
    cell.model =  [self.leftArr safeObjectAtIndex:indexPath.row];;;
    return cell;

}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    if (scrollView == self.scrollView) {
        
        _searchBar.progress = scrollView.contentOffset.y/64;
        CGFloat contentOffsetY = scrollView.contentOffset.y;
        
        if (contentOffsetY >= bannerHight-44) {
            
            [UIView animateWithDuration:0.2 animations:^{
                self.scrollView.contentOffset = CGPointMake(0, bannerHight-44);
            }];
        }
        
    }
    if ([scrollView isKindOfClass:[UITableView class]]) {
        
        CGFloat contentOffsetY = scrollView.contentOffset.y;
        
        if (contentOffsetY <= 0) {
            [UIView animateWithDuration:0.5 animations:^{
                self.scrollView.contentOffset = CGPointMake(0, 0);
            }];
            
            //            [self.scrollView scrollRectToVisible:CGRectMake(0, 0, self.scrollView.width , self.scrollView.height) animated:YES];
            
        } else {
            
            [UIView animateWithDuration:0.5 animations:^{
                self.scrollView.contentOffset = CGPointMake(0, bannerHight-44);
            }];
        }
        
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
//    CategoryModel *result = [self.dataArr safeObjectAtIndex:indexPath.row];
//    //    CategoryModel *result = self.dataArr[indexPath.row];
//    self.rightArr = result.subcategories;
//    if (tableView == self.leftTableView) {
//        [self.rightTableView reloadData]; //刷新右边表格
//    }
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    
}

#pragma mark - SDCycleScrollViewDelegate
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index{
//    
//    NSString *jumpURLStr = [self.bannerArr[index] jumpUrl];
//    if ([jumpURLStr hasPrefix:@"#"]) return;
//    BaseWebViewController *webView =[[BaseWebViewController alloc]init];
//    [webView loadHttpRequestWithUrl:jumpURLStr];
//    [self.navigationController pushViewController:webView animated:YES];
    
}
#pragma mark - Setter && Getter Methods
- (JYHomeTableViewProxy *)homeRightTableViewProxy {
    if (_homeRightTableViewProxy == nil){
        JYWeakSelf;
        _homeRightTableViewProxy = [[JYHomeTableViewProxy alloc] init];
        _homeRightTableViewProxy.ShopHandlerSelectBlock =  ^(BOOL isSelected,NSIndexPath *indexPath){ //选中
        
            [weakSelf.viewModel selectProductAtIndexPath:indexPath isSelected:isSelected];
        };
        _homeRightTableViewProxy.ShopCartHandlerChangeCountBlock = ^(NSInteger count, NSIndexPath *indexPath){ //数量的变化
            
         [weakSelf.viewModel changeCountAtIndexPath:indexPath count:count];
        };
        
    }
    return _homeRightTableViewProxy;
}


- (UITableView *)leftTableView{
    
    if (!_leftTableView) {
        
        _leftTableView = [self setTableViewFrame:CGRectMake(0, CGRectGetMaxY(self.funView.frame)+10, leftTableWidth,tableViewHeight) rowHeight:kTableView_rowHeight NibName:@"JYHomeLeftCell" Identifier:@"leftCellID"];
        _leftTableView.bounces = NO;
        _leftTableView.delegate = self;
        _leftTableView.dataSource = self;
        _leftTableView.showsVerticalScrollIndicator = NO;
        
    }
    return _leftTableView;
}
- (UITableView *)rightTableView{
    
    if (!_rightTableView) {
        _rightTableView = [self setTableViewFrame:CGRectMake(leftTableWidth, CGRectGetMaxY(self.funView.frame)+10, rightTableWidth,tableViewHeight) rowHeight:90 NibName:@"JYPublicCell" Identifier:@"RightCellID"];
        _rightTableView.decelerationRate = UIScrollViewDecelerationRateFast;
        _rightTableView.decelerationRate = 0.1;
        _rightTableView.delegate = self.homeRightTableViewProxy;
        _rightTableView.dataSource = self.homeRightTableViewProxy;
        _rightTableView.tableFooterView = [UIView new];
        _rightTableView.showsVerticalScrollIndicator = NO;
        
    }
    return _rightTableView;
    
}
- (UITableView *)setTableViewFrame:(CGRect)frame rowHeight:(CGFloat)rowHeight NibName:(NSString *)nibName Identifier:(NSString *)Identifier{

    UITableView *tableView =  [[UITableView alloc] initWithFrame:frame];
    tableView.rowHeight = rowHeight;
    [tableView registerNib:[UINib nibWithNibName:nibName bundle:nil] forCellReuseIdentifier:Identifier];
    return tableView;
}

- (UIScrollView *)scrollView{
    
    if (!_scrollView) {
        _scrollView = [[UITableView alloc]initWithFrame:CGRectMake(0, 20, Screen_Width, Screen_Height-49-20)];
        _scrollView.delegate = self;
        _scrollView.tableHeaderView = self.header;
        _scrollView.tableFooterView =[UIView new];
        _scrollView.backgroundColor = kBgColor;
        _scrollView.bounces = NO;
        _scrollView.contentSize = CGSizeMake(Screen_Width, scrollViewContentHeight);
    }
    return _scrollView;
}
- (JYHeaderView *)header{
    
    if (!_header) {
        _header =  [JYHeaderView headerView:(CGRect){0, 0, Screen_Width, bannerHight}];
        _header.delegate = self;
    }
    return _header;
    
}
- (JYFunView *)funView{
    
    if (!_funView) {

        _funView = [[JYFunView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.header.frame), Screen_Width, funHight)];
    
        _funView.FunDidSelectItemAtIndexPath = ^(NSArray *leftArr){
      
            NSLog(@"___________");
        };
    }
    return _funView;
}

- (UILabel *)nameLabel{
    
    if (!_nameLabel) {
        
        _nameLabel = [UILabel labelText:@"龙门客栈" fontSize:14 textColor:k3Color textAlignment:NSTextAlignmentCenter];
        _nameLabel.layer.cornerRadius = 18;
        _nameLabel.layer.masksToBounds = YES;
        _nameLabel.frame =CGRectMake(10, 25, 100, 32);
        _nameLabel.backgroundColor = [UIColor colorWithHexString:@"999999" alpha:.5];
    }
    return _nameLabel;
    
}

- (JYHomeViewModel *)viewModel{
    if (!_viewModel) {
        _viewModel =[[JYHomeViewModel alloc]init];
        _viewModel.delegate = self;
    }
    return _viewModel;
    
}
- (NSMutableArray *)rightArr{
    
    if (!_rightArr) {
        _rightArr = [NSMutableArray array];
    }
    return _rightArr;
}
- (NSMutableArray *)bannerArr{

    if (!_bannerArr) {
        _bannerArr = [NSMutableArray array];
    }
    return _bannerArr;
}
- (NSMutableArray *)leftArr{

    if (!_leftArr) {
        _leftArr = [NSMutableArray array];
    }
    return _leftArr;

}
@end
